import requests
from lxml.html import etree

# 1.拿到页面源代码
keyword = input("search: ")
url = "https://shanghai.zbj.com/search/service/?kw=%s&r=1" % keyword
resp = requests.get(url, headers={"User-agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36"})
content = resp.text

# 2.提取和解析数据
tree = etree.HTML(content)
divs = tree.xpath('''//*[@id="__layout"]/div/div[3]/div/div[3]/div[4]/div[1]/div''')
print("\n猪八戒主页： https://shanghai.zbj.com/ \n猪八戒搜索页面： %s \n\n" % url)
for div in divs:
    price = div.xpath('''./div[3]/div[1]/span/text()''')[0].strip('￥')
    title = div.xpath('''.//div[3]/a/text()''')[0]
    href = div.xpath('''.//div[3]/a/@href''')[0]
    com_name = div.xpath('''./a/div[2]/div[1]/div/text()''')[0]
    com_loc = div.xpath('''./div[3]/div[1]/div/text()''')[0].strip()
    print("%s\n价格：%s\t公司：%s（%s）\n%s\n" % (title, price, com_name, com_loc, href))
